﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using BeautyTech.WebSite.Models.Blogs;
using BeautyTech.Core.Domain.Blogs;
using BeautyTech.Services.Blogs;
using AutoMapper;
using BeautyTech.Core;
using PagedList;

namespace BeautyTech.WebSite.Controllers
{
    public class BlogController : Controller
    {

        #region Fields

        private readonly IBlogService _blogService;

        #endregion

        #region Ctor

        public BlogController(IBlogService blogService)
        {
            this._blogService = blogService;
        }

        #endregion

        #region Utilities

        #endregion

        #region Methods
        //
        // GET: /Blog/
        public ActionResult Index(int? page)
        {
            // return a 404 if user browses to before the first page
            if (page.HasValue && page < 1)
                return HttpNotFound();

            // retrive the blog list from the database
            //IPagedList<BlogPost> blogPosts = _blogService.GetAllBlogPosts(null, null, pageNumber, PageSize);
            IEnumerable<BlogPost> blogPosts = _blogService.GetAllBlogPosts();

            // Mapping "IEnumerable<BlogPost>" to ViewModel "IEnumerable<BlogPostListModel>"
            Mapper.CreateMap<BlogPost, BlogPostListModel>();
            IEnumerable<BlogPostListModel> ListModel = Mapper.Map<IEnumerable<BlogPost>, IEnumerable<BlogPostListModel>>(blogPosts);

            // page the list
            const int pageSize = 6;
            var listPaged = ListModel.ToPagedList(page ?? 1, pageSize);

            // return a 404 if user browses to pages beyond last page. special case first page if no items exist
            if (listPaged.PageNumber != 1 && page.HasValue && page > listPaged.PageCount)
                return HttpNotFound();

            return View(listPaged);
        }

        //
        // GET: /Blog/Details/5
        public ActionResult Details(int id)
        {
            var blogPost = _blogService.GetBlogPostById(id);
            if (blogPost == null ||
                (blogPost.StartDate.HasValue && blogPost.StartDate.Value >= DateTime.UtcNow) ||
                (blogPost.EndDate.HasValue && blogPost.EndDate.Value <= DateTime.UtcNow))
                return RedirectToRoute("HomePage");

            // Mapping "BlogPost" to ViewModel "BlogPostModel"
            Mapper.CreateMap<BlogPost, BlogPostModel>();
            BlogPostModel blogPostModel = Mapper.Map<BlogPost, BlogPostModel>(blogPost);

            return View(blogPostModel);
        }
        #endregion


    }
}
